package com.sduept.nwld.dataserver.controller.statistics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.nwld.dataserver.manager.statistics.CounterMeasuresManager;
import com.sduept.nwld.dataserver.model.countanalyse.ProtectCounterMeasure;
import com.sduept.nwld.dataserver.model.countanalyse.ProtectCounterMeasureSub;

@Named
@ViewScoped
public class CounterMeasuresController extends AbstractController {

	private static final long serialVersionUID = -3413031493199876029L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private CounterMeasuresManager manager;

	private List<ProtectCounterMeasureSub> protectCounterMeasureSubs = new ArrayList<ProtectCounterMeasureSub>();
	private ProtectCounterMeasureSub protectCounterMeasureSub = new ProtectCounterMeasureSub();
	private ProtectCounterMeasureSub selectProtectCounterMeasureSub = new ProtectCounterMeasureSub();

	private List<ProtectCounterMeasure> protectCounterMeasures = new ArrayList<ProtectCounterMeasure>();
	private ProtectCounterMeasure protectCounterMeasure = new ProtectCounterMeasure();
	private ProtectCounterMeasure selectedProtectCounterMeasure = new ProtectCounterMeasure();

	private List<String> protectCounterMeasureNames = new ArrayList<String>();
	private String protectCounterMeasureName = "";
	private String measureName = "";

	private List<Integer> years = new ArrayList<Integer>();
	private List<String> subCompanys = new ArrayList<String>();
	private String subCompany = "";

	private StreamedContent templateFile;

	@PostConstruct
	private void init() {
		protectCounterMeasures = manager.findAllProtectCounterMeasure();
		protectCounterMeasureSubs = manager.findAllProtectCounterMeasureSub();
		protectCounterMeasureNames = manager.getAllProtectCounterMeasureNames();
		subCompanys = manager.getSubcompany();
	}

	public void reload() {
		subCompany = "";
		measureName = "";
		subCompanys = manager.getSubcompany();
		protectCounterMeasureNames = manager.getAllProtectCounterMeasureNames();
		protectCounterMeasureSubs = manager.findAllProtectCounterMeasureSub();
	}

	public String getProtectCounterMeasureName(String pid) {
		String name = "";
		for (ProtectCounterMeasure bean : protectCounterMeasures) {
			if (pid.equals(bean.getId())) {
				name = bean.getName();
			}
		}
		return name;
	}

	public String getIdByCounterMeasureName(String name) {
		String id = "";
		List<ProtectCounterMeasure> counterMeasures = manager.getProtectCounterMeasureByName(name);
		if (counterMeasures.size() != 0) {
			ProtectCounterMeasure counterMeasure = counterMeasures.get(0);
			id = counterMeasure.getId();
		}
		return id;
	}

	public void preCreatProtectCounterMeasure() {
		protectCounterMeasure = new ProtectCounterMeasure();
	}

	public void editProtectCounterMeasure() {
		protectCounterMeasure = selectedProtectCounterMeasure;
	}

	public void saveProtectCounterMeasure() {
		if (protectCounterMeasure != null) {
			ProtectCounterMeasure pcm = manager.create(protectCounterMeasure);
			if (protectCounterMeasure.getId() != null) {
				protectCounterMeasures.set(protectCounterMeasures.indexOf(protectCounterMeasure),pcm);
				selectedProtectCounterMeasure = new ProtectCounterMeasure();
			} else {
				protectCounterMeasures.add(pcm);
			}
			protectCounterMeasureNames = manager.getAllProtectCounterMeasureNames();
			addSuccessMessage("保存成功");
		}
	}

	public void deleteProtectCounterMeasure() {
		if (selectedProtectCounterMeasure != null && !selectedProtectCounterMeasure.getId().isEmpty()) {
			manager.deleteProtectCounterMeasureById(selectedProtectCounterMeasure.getId());
			protectCounterMeasures.remove(selectedProtectCounterMeasure);
			addSuccessMessage("删除成功！");
			selectedProtectCounterMeasure = new ProtectCounterMeasure();
		}
	}

	public void preCreatProtectCounterMeasureSub() {
		protectCounterMeasureSub = new ProtectCounterMeasureSub();
	}

	public void editProtectCounterMeasureSub() {
		protectCounterMeasureName = getProtectCounterMeasureName(selectProtectCounterMeasureSub.getPid());
		protectCounterMeasureSub = selectProtectCounterMeasureSub;
	}

	public void saveProtectCounterMeasureSub() {
		if (protectCounterMeasureSub != null) {
			if (protectCounterMeasureSub.getId() != null) {// 编辑
				editProtectCounterMeasureSubSum(protectCounterMeasureSub);
				ProtectCounterMeasureSub pcmb = manager.create(protectCounterMeasureSub);
				protectCounterMeasureSubs.set(protectCounterMeasureSubs.indexOf(protectCounterMeasureSub), pcmb);
				selectProtectCounterMeasureSub = new ProtectCounterMeasureSub();
			} else {// 新建
				String pid = getIdByCounterMeasureName(protectCounterMeasureName);
				protectCounterMeasureSub.setPid(pid);
				if (isNotExit(protectCounterMeasureSub)) {
					protectCounterMeasureSub.setOverdueAmount(0);
					manager.create(protectCounterMeasureSub);
					protectCounterMeasureSubs.add(protectCounterMeasureSub);
					// 新建反措项目的每一年的数据
					createProtectCounterMeasureSubByYear(protectCounterMeasureSub);
				} else {
					addErrorMessage("该信息已存在，添加失败！");
					return;
				}
			}
			addSuccessMessage("保存成功");
			queryByCondition();
		}
	}

	public void editProtectCounterMeasureSubSum(ProtectCounterMeasureSub pcmb) {
		String pid = pcmb.getPid();
		String company = pcmb.getCompany();
		int y = pcmb.getYear();
		List<ProtectCounterMeasureSub> newPcmbs = manager.getProtectCounterMeasureSubByCondition(y, pid, company);
		ProtectCounterMeasureSub newPcmb = new ProtectCounterMeasureSub();
		if(newPcmbs.size()!=0) {
			newPcmb = newPcmbs.get(0);
		} 
		int newAmount = pcmb.getAmount() - newPcmb.getAmount();
		int newOntimeAmount = pcmb.getOntimeAmount() - newPcmb.getOntimeAmount();
		List<ProtectCounterMeasureSub> plist = manager.getProtectCounterMeasureSubByCondition(0, pid, company);
		ProtectCounterMeasureSub pSum = new ProtectCounterMeasureSub();
		if(plist.size()!=0) {
			pSum = plist.get(0);
			pSum.setAmount(pSum.getAmount() + newAmount);
			pSum.setOntimeAmount(pSum.getOntimeAmount() + newOntimeAmount);
			manager.create(pSum);
			protectCounterMeasureSubs.set(protectCounterMeasureSubs.indexOf(pSum), pSum);
		}
	}
	
	private boolean isNotExit(ProtectCounterMeasureSub p) {
		boolean flag = false;
		String pid = p.getPid();
		String company = p.getCompany();
		int y = p.getYear();
		List<ProtectCounterMeasureSub> protectCounterMeasureSubList = manager.getProtectCounterMeasureSubByCondition(y, pid, company);
		if (protectCounterMeasureSubList.size() == 0) {
			// 当前记录不存在，可以添加
			flag = true;
		}
		return flag;
	}

	public void createProtectCounterMeasureSubByYear(ProtectCounterMeasureSub p) {
		// 获取返措项目的年份
		List<ProtectCounterMeasure> protectCounterMeasures = manager.getProtectCounterMeasureById(p.getPid());
		if (protectCounterMeasures.size() != 0) {
			ProtectCounterMeasure protectCounterMeasure = protectCounterMeasures.get(0);
			getCounterMeasureYears(protectCounterMeasure);
		}
		if (p.getYear() == 0) {
			for (int i = years.get(0); i <= years.get(years.size() - 1); i++) {
				ProtectCounterMeasureSub pcm = new ProtectCounterMeasureSub();
				pcm.setPid(p.getPid());
				pcm.setCompany(p.getCompany());
				pcm.setYear(i);
				pcm.setAmount(0);
				pcm.setOntimeAmount(0);
				pcm.setOverdueAmount(0);
				manager.create(pcm);
				protectCounterMeasureSubs.add(pcm);
			}
		} else {
			for (int i = years.get(0); i <= years.get(years.size() - 1); i++) {
				if(i != p.getYear()) {
					ProtectCounterMeasureSub pcm = new ProtectCounterMeasureSub();
					pcm.setPid(p.getPid());
					pcm.setCompany(p.getCompany());
					pcm.setYear(i);
					pcm.setAmount(0);
					pcm.setOntimeAmount(0);
					pcm.setOverdueAmount(0);
					manager.create(pcm);
					protectCounterMeasureSubs.add(pcm);
				}
			}
			// 新建的年份不为0，则新建或者编辑年份为0的记录
			String pid = p.getPid();
			String company = p.getCompany();
			List<ProtectCounterMeasureSub> protectCounterMeasureSubList = manager.getProtectCounterMeasureSubByCondition(0, pid, company);
			ProtectCounterMeasureSub pcm = new ProtectCounterMeasureSub();
			if (protectCounterMeasureSubList.size() == 0) {
				pcm.setAmount(p.getAmount());
				pcm.setCompany(p.getCompany());
				pcm.setOntimeAmount(p.getOntimeAmount());
				pcm.setOverdueAmount(0);
				pcm.setPid(p.getPid());
				pcm.setYear(0);
			} else {
				pcm = protectCounterMeasureSubList.get(0);
				pcm.setAmount(pcm.getAmount()+p.getAmount());
				pcm.setOntimeAmount(pcm.getOntimeAmount()+p.getOntimeAmount());
			}
			manager.create(pcm);
		}
	}

	public void deleteProtectCounterMeasureSub() {
		if (selectProtectCounterMeasureSub != null && !selectProtectCounterMeasureSub.getId().isEmpty()) {
			manager.deleteProtectCounterMeasureSubById(selectProtectCounterMeasureSub.getId());
			protectCounterMeasureSubs.remove(selectProtectCounterMeasureSub);
			addSuccessMessage("删除成功");
			deleteProtectCounterMeasureSub(selectProtectCounterMeasureSub);
			selectProtectCounterMeasureSub = new ProtectCounterMeasureSub();
		}
	}

	public void deleteProtectCounterMeasureSub(ProtectCounterMeasureSub p) {
		String pid = p.getPid();
		String company = p.getCompany();
		List<ProtectCounterMeasureSub> ps = new ArrayList<ProtectCounterMeasureSub>();
		if (p.getYear() == 0) {
			// 全部删除
			ps = manager.query(pid, company);
			if(ps.size() != 0) {
				for (ProtectCounterMeasureSub protectCounterMeasureSub : ps) {
					manager.deleteProtectCounterMeasureSubById(protectCounterMeasureSub.getId());
					protectCounterMeasureSubs.remove(protectCounterMeasureSub);
				}
			}
		} else {
			// 仅删除该条记录，并修改year=0的已完成数据
			ps = manager.getProtectCounterMeasureSubByCondition(0, pid, company);
			if (ps.size() != 0) {
				ProtectCounterMeasureSub pps = ps.get(0);
				pps.setAmount(pps.getAmount() - p.getAmount());
				pps.setOntimeAmount(pps.getOntimeAmount() - p.getOntimeAmount());
				manager.create(pps);
				protectCounterMeasureSubs.set(protectCounterMeasureSubs.indexOf(pps), pps);
			}
		}
	}

	public List<String> completeCounterMeasures(String query) {
		return protectCounterMeasureNames;
	}

	public List<String> completeSubCompany(String query) {
		return subCompanys;
	}

	public void getCounterMeasure(SelectEvent event) {
		String item = (String) event.getObject();
		List<ProtectCounterMeasure> counterMeasures = manager
				.getProtectCounterMeasureByName(item);
		if (counterMeasures.size() != 0) {
			ProtectCounterMeasure counterMeasure = counterMeasures.get(0);
			getCounterMeasureYears(counterMeasure);
		}
	}

	public void getCounterMeasureYears(ProtectCounterMeasure counterMeasure) {
		years.clear();
		Date startDate = counterMeasure.getStartDate();
		Date endDate = counterMeasure.getEndDate();
		Calendar c = Calendar.getInstance();
		c.setTime(startDate);
		int startYear = c.get(Calendar.YEAR);
		c.setTime(endDate);
		int endYear = c.get(Calendar.YEAR);
		for (int year = startYear; year <= endYear; year++) {
			years.add(year);
		}
	}

	/**
	 * 文件下载
	 */
	public void fileDownloadView() {
		InputStream stream = null;
		try {
			stream = new FileInputStream(new File(
					pros.getTempletePath() + "protectCounterMeasure.xlsx"));
//			stream = new FileInputStream(new File(
//					pros.getTempletePath() + "protectCounterMeasure.xlsx"));
			templateFile = new DefaultStreamedContent(stream, "xlsx",
					"protectCounterMeasure.xlsx");
		} catch (FileNotFoundException e) {
			addErrorMessage("下载文件失败，请联系技术人员！");
			e.printStackTrace();
		}
	}

	public void chooseEquipment() {
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", true);
		options.put("width", 600);
		options.put("height", 200);

		Map<String, List<String>> params = new HashMap<>();
		List<String> param = new ArrayList<>();
		param.add("1"); // 设置去除前几行
		params.put("ingnoreRows", param);
		// openDialog("/ui/common/upload_excel_dialog", params, options);
		openDialog("/ui/common/upload_excel_define", params, options);
	}

	public void onSelectorChosen(SelectEvent event) {
		List<List<String>> objs = (List<List<String>>) event.getObject();
		List<ProtectCounterMeasureSub> temp = new ArrayList<>();
		try {
			for (List<String> list : objs) {
				ProtectCounterMeasureSub pcms = new ProtectCounterMeasureSub();
				int year = NumberFormat.getInstance()
						.parse(list.get(5).toString()).intValue();
				if (year > 1970 && year < 2200) {
					String name = list.get(0);
					String id = getIdByCounterMeasureName(name);
					pcms.setPid(id);
					pcms.setCompany(list.get(1));
					pcms.setAmount(Integer.parseInt(list.get(2)));
					pcms.setOntimeAmount(Integer.parseInt(list.get(3)));
					pcms.setOverdueAmount(Integer.parseInt(list.get(4)));
					pcms.setYear(year);
					if (isNotExit(pcms)) {
						temp.add(pcms);
					}
				} else {
					addErrorMessage("年份输入错误！");
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("表格数字有误，请仔细核对！");
			return;
		}
		for (ProtectCounterMeasureSub pcm : temp) {
			manager.create(pcm);
		}
		addSuccessMessage("文件上传成功！");
		protectCounterMeasureSubs = manager.findAllProtectCounterMeasureSub();
	}

	public void queryByCondition() {
		String pid = "";
		if (!"".equals(measureName)) {
			pid = getIdByCounterMeasureName(measureName);
		}
		protectCounterMeasureSubs = manager.query(pid, subCompany);
	}

	public void reset() {
		measureName = "";
		subCompany = "";
		queryByCondition();
	}
	
	public void onRowSelect(SelectEvent event){
		selectProtectCounterMeasureSub = (ProtectCounterMeasureSub) event.getObject();
	}
	
	public void onRowSelectRadio(SelectEvent event){
		selectedProtectCounterMeasure = (ProtectCounterMeasure) event.getObject();
	}
	
	public List<ProtectCounterMeasure> getProtectCounterMeasures() {
		return protectCounterMeasures;
	}

	public void setProtectCounterMeasures(
			List<ProtectCounterMeasure> protectCounterMeasures) {
		this.protectCounterMeasures = protectCounterMeasures;
	}

	public ProtectCounterMeasure getProtectCounterMeasure() {
		return protectCounterMeasure;
	}

	public void setProtectCounterMeasure(
			ProtectCounterMeasure protectCounterMeasure) {
		this.protectCounterMeasure = protectCounterMeasure;
	}

	public ProtectCounterMeasure getSelectedProtectCounterMeasure() {
		return selectedProtectCounterMeasure;
	}

	public void setSelectedProtectCounterMeasure(
			ProtectCounterMeasure selectedProtectCounterMeasure) {
		this.selectedProtectCounterMeasure = selectedProtectCounterMeasure;
	}

	public List<String> getProtectCounterMeasureNames() {
		return protectCounterMeasureNames;
	}

	public void setProtectCounterMeasureNames(
			List<String> protectCounterMeasureNames) {
		this.protectCounterMeasureNames = protectCounterMeasureNames;
	}

	public String getProtectCounterMeasureName() {
		return protectCounterMeasureName;
	}

	public void setProtectCounterMeasureName(String protectCounterMeasureName) {
		this.protectCounterMeasureName = protectCounterMeasureName;
	}

	public List<ProtectCounterMeasureSub> getProtectCounterMeasureSubs() {
		return protectCounterMeasureSubs;
	}

	public void setProtectCounterMeasureSubs(
			List<ProtectCounterMeasureSub> protectCounterMeasureSubs) {
		this.protectCounterMeasureSubs = protectCounterMeasureSubs;
	}

	public ProtectCounterMeasureSub getProtectCounterMeasureSub() {
		return protectCounterMeasureSub;
	}

	public void setProtectCounterMeasureSub(
			ProtectCounterMeasureSub protectCounterMeasureSub) {
		this.protectCounterMeasureSub = protectCounterMeasureSub;
	}

	public ProtectCounterMeasureSub getSelectProtectCounterMeasureSub() {
		return selectProtectCounterMeasureSub;
	}

	public void setSelectProtectCounterMeasureSub(
			ProtectCounterMeasureSub selectProtectCounterMeasureSub) {
		this.selectProtectCounterMeasureSub = selectProtectCounterMeasureSub;
	}

	public List<String> getSubCompanys() {
		return subCompanys;
	}

	public void setSubCompanys(List<String> subCompanys) {
		this.subCompanys = subCompanys;
	}

	public List<Integer> getYears() {
		return years;
	}

	public void setYears(List<Integer> years) {
		this.years = years;
	}

	public StreamedContent getTemplateFile() {
		return templateFile;
	}

	public void setTemplateFile(StreamedContent templateFile) {
		this.templateFile = templateFile;
	}

	public String getSubCompany() {
		return subCompany;
	}

	public void setSubCompany(String subCompany) {
		this.subCompany = subCompany;
	}

	public String getMeasureName() {
		return measureName;
	}

	public void setMeasureName(String measureName) {
		this.measureName = measureName;
	}

}
